<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-header class="header-container">
          <div class="logo">
            <img src="../img/yz.webp" alt="永泽游戏网" />
            <span class="yz">欢迎使用永泽游戏网</span>
          </div>
          <div class="header-right">
            <el-button type="danger" @click="logout">退出登录</el-button>
          </div>
        </el-header>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-scrollbar>
            <el-menu>
              <el-sub-menu index="1">
                <template #title>
                  <el-icon><message /></el-icon>
                </template>
                <el-menu-item-group>
                  <el-menu-item index="1-1">
                    <router-link to="/profile">修改个人信息</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-2">
                    <router-link to="/upload">上传游戏</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-3">
                    <router-link to="/gamelist">返回主页</router-link>
                  </el-menu-item>
                </el-menu-item-group>
              </el-sub-menu>
            </el-menu>
          </el-scrollbar>
        </el-aside>
        <el-main>
          <el-card class="upload-card">
            <h2>上传游戏</h2>
            <el-form :model="form" label-width="120px" class="upload-form">
              <!-- 游戏名称 -->
              <el-form-item label="游戏名称">
                <el-input v-model="form.name" placeholder="请输入游戏名称"></el-input>
              </el-form-item>

              <!-- 游戏分类 -->
              <el-form-item label="游戏分类">
                <el-input v-model="form.category" placeholder="请输入游戏分类名称"></el-input>
              </el-form-item>

              <!-- 游戏简介 -->
              <el-form-item label="游戏简介">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入游戏简介"
                ></el-input>
              </el-form-item>

              <!-- 游戏封面图片 -->
              <el-form-item label="游戏封面">
                <el-upload
                  class="upload-cover"
                  ref="coverUpload"
                  :http-request="uploadCoverFile"
                  :on-success="handleCoverSuccess"
                  :before-upload="beforeCoverUpload"
                  :limit="1"
                  :on-exceed="handleCoverExceed"
                >
                  <el-button type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">请上传游戏封面图片（支持 JPG/PNG 格式）</div>
                  </template>
                </el-upload>
              </el-form-item>

              <!-- 开发商 -->
              <el-form-item label="开发商">
                <el-input v-model="form.developer" placeholder="请输入开发商"></el-input>
              </el-form-item>

              <!-- 支持的平台 -->
              <el-form-item label="支持平台">
                <el-input v-model="form.platform" placeholder="请输入支持平台（如 PC、手机等）"></el-input>
              </el-form-item>

              <!-- 发布日期 -->
              <el-form-item label="发布日期">
                <el-date-picker
                  v-model="form.release_date"
                  type="date"
                  placeholder="选择发布日期"
                ></el-date-picker>
              </el-form-item>

              <!-- 游戏文件上传 -->
              <el-form-item label="游戏文件">
                <el-upload
                  ref="gameUpload"
                  class="upload-file"
                  :http-request="uploadGameFile"
                  :on-success="handleFileSuccess"
                  :before-upload="beforeFileUpload"
                  :limit="1"
                  :on-exceed="handleFileExceed"
                >
                  <el-button type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">请上传游戏文件（HTML 或其他资源文件）</div>
                  </template>
                </el-upload>
              </el-form-item>

              <!-- 提交按钮 -->
              <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
  <!-- 以下代码请放入前端html文件的body内 -->

</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '../axios/request';
import { useAuthStore } from '../stores/userStore';

const store = useAuthStore();
const router = useRouter();
const route = useRoute();

const coverUpload = ref(null); // 获取封面上传组件的引用
const gameUpload = ref(null); // 获取游戏文件上传组件的引用

// 页面键
const pageKey = computed(() => {
  const storedPageKey = sessionStorage.getItem('pageKey');
  return storedPageKey || `${route.path || '/upload'}-${Math.random().toString(36).substr(2, 9)}`;
});

// 表单数据
const form = ref({
  name: '', // 游戏名称
  category: '', // 游戏分类名称
  description: '', // 游戏简介
  image_url: '', // 游戏封面图片 URL
  developer: '', // 开发商
  platform: '', // 支持的平台
  release_date: '', // 发布日期
  file_url: '', // 游戏文件 URL
});

// 上传前检查 - 封面图片
const beforeCoverUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  const isSizeValid = file.size / 1024 / 1024 < 5; // 文件大小限制为 5MB

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片');
  }
  if (!isSizeValid) {
    ElMessage.error('图片大小不能超过 5MB');
  }

  return isImage && isSizeValid;
};

// 封面图片超出限制时的回调
const handleCoverExceed = () => {
  ElMessage.warning('只能上传一个封面图片');
};

// 封面图片上传成功回调
const handleCoverSuccess = (response) => {
  if (response.code === 200) {
    form.value.image_url = response.data; // 假设后端返回文件 URL 在 data 字段
    ElMessage.success('封面图片上传成功');
  } else {
    ElMessage.error('封面图片上传失败');
  }
};

// 上传前检查 - 游戏文件
const beforeFileUpload = (file) => {
  const isHTML = file.type === 'text/html';
  const isSizeValid = file.size / 1024 / 1024 < 10; // 文件大小限制为 10MB

  if (!isHTML) {
    ElMessage.error('只能上传 HTML 文件');
  }
  if (!isSizeValid) {
    ElMessage.error('文件大小不能超过 10MB');
  }

  return isHTML && isSizeValid;
};

// 游戏文件超出限制时的回调
const handleFileExceed = () => {
  ElMessage.warning('只能上传一个游戏文件');
};

// 游戏文件上传成功回调
const handleFileSuccess = (response) => {
  if (response.code === 200) {
    form.value.file_url = response.data; // 假设后端返回文件 URL 在 data 字段
    ElMessage.success('游戏文件上传成功');
  } else {
    ElMessage.error('游戏文件上传失败');
  }
};

// 自定义上传封面文件
const uploadCoverFile = async (options) => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录，无法上传');
    options.onError(new Error('未登录'));
    return;
  }

  const token = store.getToken(pageKey.value);
  if (!token) {
    ElMessage.error('未登录或 Token 无效，无法上传');
    options.onError(new Error('未登录或 Token 无效'));
    return;
  }

  const formData = new FormData();
  formData.append('file', options.file);

  try {
    const response = await request({
      url: '/games/common/upload', // 修正为一致的上传接口
      method: 'post',
      data: formData,
      pageKey: pageKey.value,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    if (response.data.code === 200) {
      options.onSuccess(response.data);
    } else {
      options.onError(new Error(response.data.msg || '上传失败'));
    }
  } catch (err) {
    console.error('上传失败:', err.response?.data || err);
    options.onError(err);
    ElMessage.error('上传失败，请检查网络');
  }
};

// 自定义上传游戏文件
const uploadGameFile = async (options) => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录，无法上传');
    options.onError(new Error('未登录'));
    return;
  }

  const token = store.getToken(pageKey.value);
  if (!token) {
    ElMessage.error('未登录或 Token 无效，无法上传');
    options.onError(new Error('未登录或 Token 无效'));
    return;
  }

  const formData = new FormData();
  formData.append('file', options.file);

  try {
    const response = await request({
      url: '/games/common/upload', // 修正为一致的上传接口
      method: 'post',
      data: formData,
      pageKey: pageKey.value,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    if (response.data.code === 200) {
      options.onSuccess(response.data);
    } else {
      options.onError(new Error(response.data.msg || '上传失败'));
    }
  } catch (err) {
    console.error('上传失败:', err.response?.data || err);
    options.onError(err);
    ElMessage.error('上传失败，请检查网络');
  }
};

// 提交表单
const submitForm = async () => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录，无法提交');
    router.push('/login');
    return;
  }

  try {
    // 校验表单数据
    if (!form.value.name || !form.value.category) {
      ElMessage.warning('请填写游戏名称和分类');
      return;
    }

    const response = await request({
      url: '/games-detail/save',
      method: 'post',
      data: {
        name: form.value.name,
        category: form.value.category,
        description: form.value.description,
        imageUrl: form.value.image_url,
        releaseDate: form.value.release_date ? new Date(form.value.release_date).toISOString().split('T')[0] : '',
        platform: form.value.platform,
        gameUrl: form.value.file_url,
        developer: form.value.developer,
      },
      pageKey: pageKey.value,
    });

    if (response.data.code === 200) {
      ElMessage.success('游戏上传成功，等待管理员审核');
      resetForm();
    } else {
      console.error('提交失败:', response.data.msg);
      ElMessage.error('提交失败，请重试');
    }
  } catch (err) {
    console.error('提交失败:', err.response?.data || err);
    ElMessage.error('提交失败，请检查网络');
  }
};

// 重置表单
const resetForm = () => {
  form.value = {
    name: '',
    category: '',
    description: '',
    image_url: '',
    developer: '',
    platform: '',
    release_date: '',
    file_url: '',
  };
  coverUpload.value.clearFiles();
  gameUpload.value.clearFiles();
  ElMessage.info('表单已重置');
};

// 退出登录
const logout = () => {
  // 清除本地存储中的 token 或用户信息
  request({
    url: '/login/logout',
    method: 'get',
    pageKey: pageKey.value,
  })
    .then((res) => {
      if (res.data.code === 200) {
              // 提示用户退出成功
        ElMessage({
          message: '退出登录成功',
          type: 'success',
        });
        store.logout(pageKey.value);
        // 跳转到登录页面
        router.push('/');
      } else {
        ElMessage.error('退出登录失败');
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage.error('请求失败，请检查网络');
    });
  ElMessage.success('退出成功');
  router.push('/login');
};

// 初始化
onMounted(() => {
  store.initialize();
  const storedPageKey = sessionStorage.getItem('pageKey');
  if (!storedPageKey) {
    ElMessage.error('未登录，请先登录');
    router.push('/');
  }
});
</script>
<style scoped>
.common-layout {
  background: linear-gradient(135deg, #f4f6f9, #e0e7ff);
  min-height: 100vh;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.el-container {
  flex: 1;
  border-radius: 0;
  overflow: hidden;
  background: #ffffff;
}

/* Header Styling */
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(90deg, #2c3e50, #34495e);
  color: #fff;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 1000;
  height: 60px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo img {
  height: 45px;
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.yz {
  font-size: 1.4rem;
  font-weight: bold;
  color: #ffffff;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.el-button {
  font-size: 14px;
  padding: 10px 20px;
  border-radius: 8px;
  transition: background-color 0.3s ease, transform 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* Aside Styling */
.el-aside {
  width: 200px;
  background-color: #ffffff;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 60px;
  bottom: 0;
  left: 0;
  z-index: 999;
  transition: width 0.3s ease;
}

.el-menu {
  border-right: none;
  height: 100%;
}

.el-sub-menu .el-icon {
  font-size: 18px;
  color: #409eff;
}

.el-menu-item {
  font-size: 14px;
  padding: 0 20px;
}

.el-menu-item a {
  color: #2c3e50;
  text-decoration: none;
  display: block;
  width: 100%;
}

.el-menu-item:hover {
  background-color: #f0f4f8;
}

/* Main Styling */
.el-main {
  margin-left: 200px;
  padding: 80px 20px 20px;
  min-height: calc(100vh - 60px);
  background: #f4f6f9;
}

.profile-container {
  max-width: 800px;
  margin: auto;
  padding: 25px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.1);
}

.el-descriptions {
  margin-top: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  background: #f9f9f9;
}

.el-descriptions-item {
  font-size: 16px;
  padding: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.el-descriptions-item label {
  font-weight: bold;
  color: #2c3e50;
  font-size: 16px;
}

.el-descriptions-item:last-child {
  border-bottom: none;
}

.el-image {
  border-radius: 50%;
  border: 3px solid #e0e0e0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  width: 100px;
  height: 100px;
}

.el-tag {
  font-size: 14px;
  background: #409eff;
  color: white;
  border-radius: 5px;
}

.el-button.primary {
  margin: 15px 0;
  background: linear-gradient(90deg, #3498db, #2980b9);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, background 0.3s ease;
}

.el-button.primary:hover {
  background: linear-gradient(90deg, #2980b9, #3498db);
  transform: scale(1.05);
}

.el-button[type="danger"] {
  background: linear-gradient(90deg, #e74c3c, #c0392b);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, background 0.3s ease;
}

.el-button[type="danger"]:hover {
  background: linear-gradient(90deg, #c0392b, #e74c3c);
  transform: scale(1.05);
}

.avatar-uploader .el-button {
  background: linear-gradient(90deg, #2ecc71, #27ae60);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, background 0.3s ease;
}

.avatar-uploader .el-button:hover {
  background: linear-gradient(90deg, #27ae60, #2ecc71);
  transform: scale(1.05);
}

.profile-container .el-button + .el-button,
.profile-container .el-button + .avatar-uploader,
.profile-container .avatar-uploader + .el-button {
  margin-left: 15px;
}

/* Dialog Styling */
.el-dialog {
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
  padding: 20px;
  width: 500px;
}

.el-dialog-title {
  font-size: 1.4rem;
  color: #333;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-input,
.el-radio-group {
  width: 100%;
  border-radius: 5px;
  padding: 8px;
  font-size: 14px;
}

.el-input::placeholder {
  color: #bdc3c7;
}

.el-radio-group .el-radio {
  margin-right: 20px;
  font-size: 14px;
}

.dialog-footer {
  text-align: center;
  padding: 15px;
}

.el-dialog .el-button {
  font-size: 14px;
  padding: 10px 20px;
}

/* Responsive Adjustments */
@media (max-width: 1024px) {
  .el-aside {
    width: 180px;
  }

  .el-main {
    margin-left: 180px;
    padding: 80px 15px 15px;
  }

  .profile-container {
    max-width: 100%;
    padding: 20px;
  }

  .el-descriptions-item {
    font-size: 14px;
    padding: 10px;
  }

  .el-descriptions-item label {
    font-size: 14px;
  }

  .el-image {
    width: 90px;
    height: 90px;
  }
}

@media (max-width: 768px) {
  .el-container {
    flex-direction: row;
  }

  .el-aside {
    width: 60px;
  }

  .el-main {
    margin-left: 60px;
    padding: 70px 10px 10px;
  }

  .el-menu-item a {
    font-size: 12px;
    text-align: center;
  }

  .profile-container {
    padding: 15px;
  }

  .el-descriptions-item {
    font-size: 15px;
    padding: 12px;
  }

  .el-button.primary,
  .el-button[type="danger"],
  .avatar-uploader .el-button {
    padding: 12px 20px;
    font-size: 15px;
  }

  .profile-container .el-button + .el-button,
  .profile-container .el-button + .avatar-uploader,
  .profile-container .avatar-uploader + .el-button {
    margin-left: 10px;
  }
}

@media (max-width: 480px) {
  .el-aside {
    width: 50px;
  }

  .el-main {
    margin-left: 50px;
    padding: 60px 8px 8px;
  }

  .el-menu-item a {
    font-size: 10px;
  }

  .profile-container {
    padding: 10px;
  }

  .el-descriptions-item {
    font-size: 14px;
    padding: 10px;
  }

  .el-button.primary,
  .el-button[type="danger"],
  .avatar-uploader .el-button {
    padding: 10px 15px;
    font-size: 14px;
  }
}
</style>